package com.cjm.thread.zhonjianjian.cthreadlocal;


import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

public class CpuRun {
    private static AtomicLong ll = new AtomicLong();
    private static DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // 关机
//    private static String shutdown = "shutdown -s -f -t 60";
    // 重启
    private static String shutdown = "shutdown -r -t 10";

    private static String shutdownTime = "2023-12-17 06:06:06";

    private static String logLocation = "D://process.log";

    public static void main(String[] args) throws Exception {
        start();
    }

    private static boolean nowBigThanTarget(String target) {
        Date now = new Date();
        Date targetTime = null;
        try {
            targetTime = format.parse(target);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        int x = now.compareTo(targetTime);
        return x > 0;
    }


    private static void start() {
        int nThreads = Runtime.getRuntime().availableProcessors();
        ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
        for (int i = 0; i < nThreads; i++) {
            executorService.submit(() -> {
                while (true) {
                    long l = ll.get();
                    if (Long.MAX_VALUE - l < 10) {
                        ll.set(0);
                    }
                    ll.addAndGet(1);
                }
            });
        }

        final AtomicBoolean flag = new AtomicBoolean(true);
        Thread c = new Thread(() -> {
            while (flag.get()) {
                try {
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    System.err.println(e.getMessage());
                }
                print(format.format(new Date()) + ";long = " + ll.get());
                if (nowBigThanTarget(shutdownTime)) {
                    executorService.shutdownNow();
                    flag.set(false);
                    exeCmd(shutdown);
                    print("over");
                }
            }
        }, "abc");


        c.start();
    }

    /**
     * exeCmd("notepad d://abc.txt")
     *
     * @param cmd
     */
    public static void exeCmd(String cmd) {
        print("开始关机了");
        Runtime runtime = Runtime.getRuntime();
        // 仅限在Windows系统
        //shutdown -s -t 600    中600代表多少秒后关机
        try {
            Process process = runtime.exec(cmd);
            try {
                process.waitFor(12, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            print("执行完毕");
        } catch (IOException e) {
            System.err.println(e.getMessage());
        }
    }

    public static void print(String msg) {
        File file = new File(logLocation);
        try (FileWriter write = new FileWriter(file, true)) {
            write.write(System.lineSeparator() + msg);
            write.flush();
        } catch (Exception e) {
        }
    }

    public static void print1(String msg) {
        File file = new File(logLocation);
        try (FileOutputStream out = new FileOutputStream(file)) {
            if (!file.exists()) {
                file.createNewFile();
            } else {
                file.delete();
                file.createNewFile();
            }
            byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
            out.write(bytes);
            out.flush();
        } catch (Exception e) {
        }
    }
}
